package com.lalawaimai.plateform.order.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.lalawaimai.palteform.baselib.base.BaseCommonActivity;
import com.lalawaimai.palteform.baselib.http.CommonBean;
import com.lalawaimai.palteform.baselib.http.DisposeDataListener;
import com.lalawaimai.palteform.baselib.http.OkHttpException;
import com.lalawaimai.palteform.baselib.http.RequestWebInfo;
import com.lalawaimai.palteform.baselib.utils.CommonUtil;
import com.lalawaimai.palteform.baselib.utils.NullUtil;
import com.lalawaimai.plateform.R;
import com.lalawaimai.plateform.bean.DeliveryerBean;
import com.lalawaimai.plateform.constant.Constant;
import com.lalawaimai.plateform.home.HomeActivity;
import com.lalawaimai.plateform.http.WebUrl;
import com.lalawaimai.plateform.order.fragment.WaitOrderFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * 地图调度页面
 * Created by WaterWood on 2018/6/6.
 */
public class DispatchMapActivity extends BaseCommonActivity implements View.OnClickListener, RouteSearch.OnRouteSearchListener {

    private View status_bar;
    private LinearLayout ll_back;
    private TextView tv_title;
    private MapView mMapView;
    private AMap aMap;
    private CameraUpdate cameraUpdate;
    private List<DeliveryerBean> listDeliveryer;
    private ProgressDialog dialogWeb;//网络加载等待框
    private String orderId;
    private RouteSearch routeSearch;
    private List<Marker> listMark;

    @Override
    protected boolean initArgs(Bundle bundle) {
        listDeliveryer = (List<DeliveryerBean>) bundle.getSerializable("info");
        orderId = bundle.getString("orderId");
        if (NullUtil.isListEmpty(listDeliveryer) || NullUtil.isStringEmpty(orderId)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_map;
    }

    @Override
    protected void initWidget() {
        status_bar = findViewById(R.id.status_bar);
        ll_back = findViewById(R.id.ll_back);
        tv_title = findViewById(R.id.tv_title);
        mMapView = findViewById(R.id.map);
        ll_back.setOnClickListener(this);
        setStatusBarSize(this, status_bar);
        tv_title.setText("配送员位置");
        initMap();
        dialogWeb = CommonUtil.showProgressDialog(this, "正在加载");
        initSearchPath();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_back:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    private void initMap() {
        mMapView.onCreate(getSavedInstanceState());
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //开始整一个点
        ArrayList<MarkerOptions> listMarkOp = new ArrayList<>();
        listMark = new ArrayList<>();
        for (int i = 0; i < listDeliveryer.size(); i++) {
            LatLng latLng = new LatLng(listDeliveryer.get(i).getLatitude(), listDeliveryer.get(i).getLongitude());
            MarkerOptions markerOption = new MarkerOptions();
            markerOption.position(latLng);
            markerOption.draggable(false);
            markerOption.icon(BitmapDescriptorFactory.fromView(getView(i)));
            listMarkOp.add(markerOption);
            Marker marker = aMap.addMarker(markerOption);
            listMark.add(marker);
        }
        //可视化区域，将指定位置指定到屏幕中心位置
        LatLng latLng = new LatLng(listDeliveryer.get(0).getLatitude(), listDeliveryer.get(0).getLongitude());
        cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 0, 30));
        aMap.moveCamera(cameraUpdate);
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(com.amap.api.maps2d.model.Marker marker) {
                for (int i = 0; i < listMark.size(); i++) {
                    final int pos = i;
                    if (listMark.get(i).hashCode() == marker.hashCode()) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(DispatchMapActivity.this);
                        builder.setMessage("您确定要将订单分配给" + listDeliveryer.get(i).getName() + "吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestWeb(listDeliveryer.get(pos).getId());
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        AlertDialog alertDialog = builder.create();
                        alertDialog.show();
                    }
                }
                return true;
            }
        });
    }

    /**
     * 绘制标记点内容
     *
     * @return
     */
    private View getView(int position) {
        View view = View.inflate(this, R.layout.pop_map, null);
        TextView name = view.findViewById(R.id.name);
        TextView info = view.findViewById(R.id.info);
        name.setText(listDeliveryer.get(position).getName());
        info.setText("外卖:" + listDeliveryer.get(position).getOrder_takeout_num() + "单 跑腿:" + listDeliveryer.get(position).getOrder_errander_num() + "单");
        return view;
    }

    /**
     * 调度确定分配
     */
    private void requestWeb(String deliveryerId) {
        dialogWeb.show();
        String url = WebUrl.DISPATCH_TO_DELIVERYER;
        Class<?> clazz = CommonBean.class;
        List<String> list = new ArrayList<>();
        list.add("token");
        list.add("id");
        list.add("deliveryer_id");
        new RequestWebInfo(new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                dialogWeb.dismiss();
                CommonBean commonBean = (CommonBean) responseObj;
                //todo 订单分配成功后的处理，反正都是要结束的
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onFailure(Object reasonObj) {
                dialogWeb.dismiss();
                OkHttpException okHttpException = (OkHttpException) reasonObj;
                String msg = okHttpException.getEmsg().toString();
                if (msg.contains("java.net.ConnectException")) {
                    CommonUtil.showToast(DispatchMapActivity.this, "无法连接服务器，请检查您的网络");
                }else{
                    CommonUtil.showToast(DispatchMapActivity.this, msg);
                }
            }
        }).requestWeb(url, clazz, list, (String) CommonUtil.readData(this, Constant.TOKEN,Constant.STRING),orderId, deliveryerId);
    }

    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
        //回调数据在这里
        if (i == 1000) {
            if (driveRouteResult != null && driveRouteResult.getPaths() != null) {
                if (driveRouteResult.getPaths().size() > 0) {
                    final DrivePath drivePath = driveRouteResult.getPaths().get(0);
                    DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(this, aMap, drivePath, driveRouteResult.getStartPos(),driveRouteResult.getTargetPos());
                    drivingRouteOverlay.removeFromMap();
                    drivingRouteOverlay.setNodeIconVisibility(false);//隐藏转弯的节点
                    drivingRouteOverlay.addToMap();
                    drivingRouteOverlay.zoomToSpan();
                }
            }
        }
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

    }

    /**
     * 初始化搜索路径参数
     */
    private void initSearchPath() {
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);
        LatLonPoint from = new LatLonPoint(listDeliveryer.get(0).getLatitudeShop(), listDeliveryer.get(0).getLongitudeShop());
        LatLonPoint to = new LatLonPoint(listDeliveryer.get(0).getLatitudeCustomer(), listDeliveryer.get(0).getLongitudeCustomer());
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(from, to);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_DEFAULT, null, null, "");
        routeSearch.calculateDriveRouteAsyn(query);
    }
}
